/*
 *  main.c
 *  Fib
 *
 *  Created by John Bassham on 11/13/08.
 *  Copyright 2008 __MyCompanyName__. All rights reserved.
 *
 */

#include "config.h"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>

#include "bool.h"

#include "intrp.h"

#define FNAME_SZ		32

int main(const int argc, const char *argv[])
{
	if (argc <= 1) {
		puts("no file(s) given to run");
	} else {
		int i;
		char **fnames[FNAME_SZ];
		struct intrp_ops ops;
		int fname_indx = 0;
		
		memset(ops, 0, sizeof(struct intrp_ops));
		for (i = 1; i < argc; i++) {
			size_t len = strlen(argv[i]);
			if (len > 1) {
				if (argv[i][0] == '-') {
					int j;
					for (j = 0; j < len; j++) {
						switch (argv[i][j]) {
							case 'i':
								ops.is_interactive = true;
								break;
							case 'p':
								break;
							default:
								printf("unrecognized option given \'-%c\'\n", argv[i][j]);
								break;
						}
					}
				} else {
					fnames[fname_indx++] = argv[i];
				}
			}
		}
		/* TODO: hack to change later */
		ops.return_type_str = "str";
		if (fname_indx > MAX_MOD_FILES) {
			puts("too many files to open");
		} else {
			int j;
			struct intrp intrp;
			bool all_valid = true;
			
			memset(intrp, 0, sizeof(struct intrp));
			for (j = 0; j < fname_indx && all_valid; j++) {
				ops.mod_files[j] = fopen(fnames[j], "r");
				if (!ops.mod_files[j]) {
					printf("%s couldn't be opened\n", fnames[j]);
					all_valid = false;
				}
			}
			if (init_intrp(&intrp, &ops)) {
				const char *rettype = get_intrp_return_type(intrp);
				void *retptr = intrp_run(intrp);
				if (rettype) {
					if (!strcasecmp(rettype, "str") || !strcasecmp(rettype, "string")) {
						puts((const char *) retptr);
					} else if (!strcasecmp(rettype, "int") || !strcasecmp(rettype, "integer")) {
						printf("%i\n", *((int *) retptr));
					} else {
						printf("unrecognized return type string \"%s\"\n", rettype);
					}
				}
			} else {
				puts("intrp initalization errors occured");
			}
		}
	}
    return 0;
}
